package com.mpgame;

import com.mpgame.common.network.NetTcpServer;
import com.mpgame.common.proto.CmdId;
import com.mpgame.common.utils.ConsulUtil;
import com.mpgame.common.utils.Log;
import com.mpgame.database.redis.manager.RedisMgr;

import java.net.InetAddress;

import com.mpgame.common.constants.Constants.CPorts;
import com.mpgame.common.manager.HandlerMgr;
import com.mpgame.handler.AuthHandler;
import com.mpgame.handler.ForwardHandler;
import com.mpgame.handler.GatewayClientHandler;
import com.mpgame.queue.MessageQueueConsumer;

public class GatewayServer 
{
    public static void main( String[] args ) throws Exception
    {
        try{
            RedisMgr.getInstance().init();


            String host = InetAddress.getLocalHost().getHostAddress();
            int port = CPorts.GATEWAY_TCP_PORT;
            // 注册本网关到 Consul
            ConsulUtil.registerAgentService("gateway-service", port);

            // 启用消息队列消费者
            String instanceId = System.getenv().getOrDefault(
                "GATEWAY_INSTANCE_ID", 
                java.net.InetAddress.getLocalHost().getHostName());
            String groupId = "mp-gateway-"+instanceId;
            MessageQueueConsumer.getInstance().start(groupId);
            
            AuthHandler authHandler = new AuthHandler();
            ForwardHandler forwardHandler = new ForwardHandler();

            HandlerMgr handlerMgr = new HandlerMgr()
                .registHandler(CmdId.GAME_AUTH_REQ, authHandler)
                .registHandler(CmdId.LOGIN_REQ, forwardHandler)
                .registHandler(CmdId.REGIST_REQ, forwardHandler)
                .registHandler(CmdId.CHAT_REQ, forwardHandler)
                .registHandler(CmdId.GAME_INITDATA_REQ, forwardHandler)
                .registHandler(CmdId.GAME_MOVE_TO_REQ, forwardHandler)
                .registHandler(CmdId.GAME_CHAT_REQ, forwardHandler)
                .registHandler(CmdId.GAME_SWITCH_SCENE_REQ, forwardHandler)
                .registHandler(CmdId.BATTLE_INVITE_REQ, forwardHandler)
                .registHandler(CmdId.BATTLE_INVITE_REFUSE_REQ, forwardHandler)
                .registHandler(CmdId.BATTLE_START_REQ, forwardHandler)
                .registHandler(CmdId.BATTLE_MATCH_REQ, forwardHandler)
                .registHandler(CmdId.BATTLE_ACTION_REQ, forwardHandler)
                .registHandler(CmdId.BATTLE_ANIMATION_FINISHED_PLAY_REQ, forwardHandler)
                ;
            GatewayClientHandler cliHandler = new GatewayClientHandler(handlerMgr);
            new NetTcpServer(CPorts.GATEWAY_TCP_PORT).start(() -> cliHandler);
            
        }catch(Exception e){
            Log.err("服务启动失败：" + e.getMessage());
        }finally{
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                Log.info("关闭服务器...");
                Log.info("服务已关闭...");
            }));
        }
    }
}
